import { ref } from 'vue';

import { defineStore } from 'pinia';

const envents = new Map();
// removeLententFuns('call_script_function_req')
// removeLententFuns('creted_open_urls')
function addLententFuns(id: string, cb: any) {
  if (envents.get(id)) {
    window.removeEventListener('message', envents.get(id));
    envents.delete(id);
  }
  envents.set(id, cb);
  window.addEventListener('message', envents.get(id));
}
function checkPlugin() {
  window.postMessage({
    type_urs: 'wtbg',
    method: 'get_add_new_prd',
    configs: [],
  });
}
export const sysStatusDataStore = defineStore('sysStatusData', () => {
  const checkPluginStatus = ref(false);
  const isIntallPlugin = ref(true);
  let isCheck: any = null;
  function $reset() {
    checkPluginStatus.value = false;
    isIntallPlugin.value = true;
    isCheck = null;
  }

  const outOpenMoberile = setTimeout(() => {
    checkPluginStatus.value = true;
    isIntallPlugin.value = false;
    clearInterval(isCheck);
    clearInterval(outOpenMoberile);
  }, 5000);

  addLententFuns('call_script_function_req', (e: any) => {
    // console.log(' e.data', e.data);
    if (
      e.data?.type_urs === 'wtbg' &&
      e.data?.method === 'getNewPrdHoter' &&
      e.data?.data === '2.0.0'
    ) {
      isIntallPlugin.value = true;
      clearTimeout(outOpenMoberile);
      clearInterval(isCheck);
    }
  });
  isCheck = setInterval(() => {
    checkPlugin();
  }, 100);
  const pathname = location.pathname;
  if (pathname === '/in-doudian-get-1688') {
    isIntallPlugin.value = true;
    clearTimeout(outOpenMoberile);
    clearInterval(isCheck);
    return;
  }
  checkPlugin();

  return {
    checkPluginStatus,
    isIntallPlugin,
    $reset,
  };
});
